<?php
require_once 'serviceprovider.php';

define("NETFONDS_HEADER_SIZE", 1);
define("NETFONDS_TIME_COL_NAME", "time");
define("NETFONDS_CLOSE_COL_NAME", "price");
define("NETFONDS_VOLUME_COL_NAME", "quantity");

class NetFonds extends ServiceProvider{
	public function __construct(){	debug();
		$this->url = "http://hopey.netfonds.no/tradedump.php?";
		$this->stockDataType = "StockData";
		$this->hasTick = TRUE;
	}
	
	public function GetStockExchangeTickers($SEname){
		debug();
	}
	
	protected function GetStockQueryString($ticker, $ts){	debug();
		$param = array(	'date' => date('Ymd', $ts),
						'paper' => $ticker,
						'csv_format' => 'csv');
		
		$qString = $this->url.http_build_query($param);
		
		return $qString;
	}
	
	public function GetStockData($ticker, $ts){	debug();
	}

	
	public function FormatData($record){	debug();
		$resultCsv = str_getcsv($record);
		if($resultCsv){
			$stockDataArray = array_combine($this->dataExported, $resultCsv);
			$ts = strtotime($stockDataArray[NETFONDS_TIME_COL_NAME] . " ".TIMEZONE_CODE) - date("Z");
			return new $this->stockDataType(date("Y-m-d H:i:s", $ts), $stockDataArray[NETFONDS_VOLUME_COL_NAME], $stockDataArray[NETFONDS_CLOSE_COL_NAME]);
		}
		return FALSE;
	}
	
	protected function GetExchangeQueryString($SEname){	debug();
		
	}
	
	protected function GetBackupFileName($fName){	debug();
		return $fName."_netfonds.zip";
	}
	
	protected function GetHeaderAndRecords($fName, $tsSkip = NULL, $cntSkip = NULL){
		$csvData = file_get_contents($fName);
		$this->records = explode(PHP_EOL, $csvData);
		$firstRow = array_shift($this->records);
		if(empty($this->dataExported)){
			$this->dataExported = str_getcsv($firstRow);
		}
		$nRec = count($this->records) - 1;	// -1 perche' l'ultima riga e' EOL
		if($nRec > 0){
			//eventuale skip:
			//1. legge il timestamp del primo record
			$stockData = array_combine($this->dataExported, str_getcsv($this->records[0]));
			$firstRecTs = strtotime($stockData[NETFONDS_TIME_COL_NAME] . " ".TIMEZONE_CODE);
			if(isset($tsSkip)){
				if($tsSkip > $firstRecTs){
					//2. se e' oltre il timestamp del primo record, esegue skip
					while($tsSkip > strtotime($stockData[NETFONDS_TIME_COL_NAME] . " ".TIMEZONE_CODE) && $nRec){
						array_shift($this->records);
						$nRec--;
						$stockData = array_combine($this->dataExported, str_getcsv($this->records[0]));
						echo "<br>skipping: ".var_dump($stockData);
					}
					
					if(isset($cntSkip)){
						while($cntSkip){
							array_shift($this->records);
							$cntSkip--;
						}
					}
				}
			}
		}
		return $nRec;
	}
	
	protected function IsLocalFileEmpty(){	debug();
		if(file_exists(PATH_PROVIDER.$this->localFileName)){
			if(count(file(PATH_PROVIDER.$this->localFileName)) > NETFONDS_HEADER_SIZE)
				return FALSE;
		}
		return TRUE;
	}
	
	protected function LocalFileDeleteRecord($nRec){	debug();
		read_and_delete_line(PATH_PROVIDER.$this->localFileName, $nRec + NETFONDS_HEADER_SIZE);
	}
}

?>